import { $ctx, $prose } from '@milkdown/kit/utils';
import { Plugin, PluginKey } from '@milkdown/kit/prose/state';
import { Decoration, DecorationSet } from '@milkdown/kit/prose/view';

/**
 * 自定义插件 1: 字数统计插件
 */
export const wordCountPlugin = $prose(() => {
  const key = new PluginKey('word-count');
  
  return new Plugin({
    key,
    state: {
      init() {
        return { words: 0, characters: 0 };
      },
      apply(tr, prev) {
        if (!tr.docChanged) return prev;
        
        const text = tr.doc.textContent;
        const words = text.trim() ? text.trim().split(/\s+/).length : 0;
        const characters = text.length;
        
        // 发送统计事件
        if (typeof window !== 'undefined') {
          window.dispatchEvent(new CustomEvent('milkdown-word-count', {
            detail: { words, characters }
          }));
        }
        
        return { words, characters };
      }
    }
  });
});

/**
 * 自定义插件 2: 高亮关键词插件
 */
export const highlightPlugin = (keywords = []) => $prose(() => {
  const key = new PluginKey('highlight-keywords');
  
  return new Plugin({
    key,
    state: {
      init(_, { doc }) {
        return DecorationSet.create(doc, findKeywords(doc, keywords));
      },
      apply(tr, set) {
        if (!tr.docChanged) return set.map(tr.mapping, tr.doc);
        return DecorationSet.create(tr.doc, findKeywords(tr.doc, keywords));
      }
    },
    props: {
      decorations(state) {
        return this.getState(state);
      }
    }
  });
});

function findKeywords(doc, keywords) {
  const decorations = [];
  
  doc.descendants((node, pos) => {
    if (node.isText) {
      const text = node.text;
      keywords.forEach(keyword => {
        let index = 0;
        while ((index = text.indexOf(keyword, index)) !== -1) {
          decorations.push(
            Decoration.inline(pos + index, pos + index + keyword.length, {
              class: 'milkdown-highlight-keyword',
              style: 'background-color: yellow; padding: 2px; border-radius: 3px;'
            })
          );
          index += keyword.length;
        }
      });
    }
  });
  
  return decorations;
}

/**
 * 自定义插件 3: 自动保存插件
 */
export const autoSavePlugin = (saveCallback, interval = 30000) => $prose(() => {
  const key = new PluginKey('auto-save');
  let saveTimer = null;
  
  return new Plugin({
    key,
    state: {
      init() {
        return { lastSaved: Date.now() };
      },
      apply(tr, prev) {
        if (!tr.docChanged) return prev;
        
        // 清除之前的定时器
        if (saveTimer) {
          clearTimeout(saveTimer);
        }
        
        // 设置新的自动保存定时器
        saveTimer = setTimeout(() => {
          const content = tr.doc.textContent;
          saveCallback(content);
        }, interval);
        
        return { lastSaved: prev.lastSaved };
      }
    },
    destroy() {
      if (saveTimer) {
        clearTimeout(saveTimer);
      }
    }
  });
});

/**
 * 自定义插件 4: 表情符号快捷插件
 */
export const emojiPlugin = $prose(() => {
  const key = new PluginKey('emoji-shortcut');
  
  const emojiMap = {
    ':smile:': '😄',
    ':heart:': '❤️',
    ':thumbsup:': '👍',
    ':fire:': '🔥',
    ':rocket:': '🚀',
    ':star:': '⭐',
    ':check:': '✅',
    ':warning:': '⚠️'
  };
  
  return new Plugin({
    key,
    props: {
      handleTextInput(view, from, to, text) {
        const { state } = view;
        const before = state.doc.textBetween(Math.max(0, from - 20), from, '\n', '\n');
        const fullText = before + text;
        
        // 检查是否匹配表情符号模式
        for (const [shortcode, emoji] of Object.entries(emojiMap)) {
          if (fullText.endsWith(shortcode)) {
            const start = from - shortcode.length + text.length;
            const tr = state.tr.replaceWith(start, to, state.schema.text(emoji));
            view.dispatch(tr);
            return true;
          }
        }
        return false;
      }
    }
  });
});

/**
 * 自定义命令插件
 */
export const customCommandsPlugin = $prose(() => {
  const key = new PluginKey('custom-commands');
  
  return new Plugin({
    key,
    props: {
      handleKeyDown(view, event) {
        // Ctrl/Cmd + Shift + D: 插入当前日期
        if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key === 'D') {
          const date = new Date().toLocaleDateString('zh-CN');
          const { state } = view;
          const tr = state.tr.insertText(date);
          view.dispatch(tr);
          return true;
        }
        
        // Ctrl/Cmd + Shift + T: 插入当前时间
        if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key === 'T') {
          const time = new Date().toLocaleTimeString('zh-CN');
          const { state } = view;
          const tr = state.tr.insertText(time);
          view.dispatch(tr);
          return true;
        }
        
        return false;
      }
    }
  });
});
